import { Injectable } from '@nestjs/common';
import { CreateCategoryDto } from './dto/create-category.dto';
import { UpdateCategoryDto } from './dto/update-category.dto';
import { PrismaService } from '../prisma/prisma.service';
import {
  HttpException,
  HttpStatus,
  ConflictException,
  NotFoundException,
} from '@nestjs/common';
import { ApiResponse } from 'src/common/reponse.interface'; // 引入统一响应格式
@Injectable()
export class CategoryService {
  constructor(private prisma: PrismaService) {}
  // 创建分类
  async create(
    createCategoryDto: CreateCategoryDto,
  ): Promise<ApiResponse<any>> {
    const { title } = createCategoryDto;
    const existingCategory = await this.prisma.category.findFirst({
      where: { title: title },
    });
    if (existingCategory) {
      throw new ConflictException('分类已存在');
    }
    const result = await this.prisma.category.create({
      data: { title: title },
    });
    return {
      statusCode: 200,
      message: '创建成功',
      data: result,
    };
  }
  // 查询所有分类
  async findAll(page?: number, pageSize?: number): Promise<ApiResponse<any>> {
    try {
      let result;
      let total;
      let totalPages;

      if (page == null || pageSize == null) {
        // 如果没有传递分页参数，查询所有数据
        result = await this.prisma.category.findMany();
        total = result.length;
        totalPages = 1;
      } else {
        // 计算跳过数量
        const skip = Number((page - 1) * pageSize);
        // 计算总数量
        total = await this.prisma.category.count();
        // 计算总页数
        totalPages = Math.ceil(total / pageSize);
        // 查询数据
        result = await this.prisma.category.findMany({
          skip,
          take: Number(pageSize),
          include: {
            images: {
              include: {
                image: {
                  select: {
                    filename: true,
                    filepath: true,
                  },
                },
              },
            },
          },
        });
      }

      const data = {
        list: result,
        total,
        totalPages,
      };
      return {
        statusCode: 200,
        message: '查询成功',
        data,
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
  // 查询单个分类
  async findOne(id: number): Promise<ApiResponse<any>> {
    try {
      const result = await this.prisma.category.findUnique({
        where: { id },
        include: {
          images: {
            include: {
              image: {
                select: {
                  filename: true,
                  filepath: true,
                },
              },
            },
          },
        },
      });
      return {
        statusCode: 200,
        message: '查询成功',
        data: result,
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
  // 更新分类
  async update(
    id: number,
    updateCategoryDto: UpdateCategoryDto,
  ): Promise<ApiResponse<any>> {
    const { title } = updateCategoryDto;
    try {
      const result = await this.prisma.category.update({
        where: { id },
        data: { title: title },
      });
      return {
        statusCode: 200,
        message: '更新成功',
        data: result,
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
  // 删除分类
  async remove(id: number): Promise<ApiResponse<any>> {
    try {
      const result = await this.prisma.category.delete({
        where: { id },
      });
      return {
        statusCode: 200,
        message: '删除成功',
        data: result,
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
  // 查询分类下的链接
  async findLink(id: number): Promise<ApiResponse<any>> {
    try {
      const result = await this.prisma.link.findMany({
        where: { categoryId: id },
        include: {
          category: true,
        },
      });
      return {
        statusCode: 200,
        message: '查询成功',
        data: result,
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
  // 通过名称查询分类
  async findByTitle(title: string): Promise<ApiResponse<any>> {
    console.log(title);
    try {
      const result = await this.prisma.category.findFirst({
        where: {
          title,
        },
      });
      if (!result) {
        throw new NotFoundException('分类不存在');
      }
      return {
        statusCode: 200,
        message: '查询成功',
        data: result,
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  // 统计各个分类下的链接数量
  async countLinks(): Promise<ApiResponse<any>> {
    try {
      // 使用 groupBy 统计每个分类下的链接数量
      const groupedLinks = await this.prisma.link.groupBy({
        by: ['categoryId'],
        _count: {
          id: true, // 统计每个 categoryId 下的链接数量
        },
      });

      // 查询所有涉及的 categoryId 的分类信息
      const categoryIds = groupedLinks.map((link) => link.categoryId);
      const categories = await this.prisma.category.findMany({
        where: {
          id: { in: categoryIds },
        },
        select: {
          id: true,
          title: true,
        },
      });

      // 合并结果，将分类信息与链接数量结合
      const result = groupedLinks.map((group) => {
        const category = categories.find((cat) => cat.id === group.categoryId);
        return {
          categoryId: group.categoryId,
          categoryTitle: category ? category.title : '未知分类',
          linkCount: group._count.id,
        };
      });

      return {
        statusCode: 200,
        message: '查询成功',
        data: result,
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
